/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.rpc.remote.grpc.registry;

import io.iec.edp.caf.common.JSONSerializer;
import io.iec.edp.caf.commons.event.StartupCompletedEvent;
import io.iec.edp.caf.commons.runtime.CafEnvironment;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.rpc.api.common.RpcChannelType;
import io.iec.edp.caf.rpc.api.entity.ServiceUnitDefinition;
import io.iec.edp.caf.rpc.api.grpc.GrpcVariable;
import io.iec.edp.caf.rpc.api.spi.ServiceCenterProvider;
import io.iec.edp.caf.rpc.api.support.RpcChannelFactory;
import io.iec.edp.caf.rpc.remote.grpc.GrpcServerInvoke;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
public class GrpcServiceRegistryListener implements ApplicationListener<StartupCompletedEvent> {
//    //服务注册
//    private ServiceRegistry serviceRegistry;
//
//    //微服务设置
//    private MsuProperties configuration;
//
//    public GrpcServiceRegistryListener(ServiceRegistry serviceRegistry, MsuProperties configuration,) {
//        this.serviceRegistry = serviceRegistry;
//        this.configuration = configuration;
//    }
    @Override
    public void onApplicationEvent(StartupCompletedEvent event) {

//        String ip = CafEnvironment.getLocalIp(this.configuration.getIp().getPrefix());

        //获取配置的grpc端口
        String port = CafEnvironment.getEnvironment().getProperty("caf-rpc.grpc.server.port");
        if (port == null || "".equals(port)) {
            port = "8088";
        }

        //组装实例注册信息
        //获取当前应用服务器下的所有SU信息
//        ServiceUnitAwareService suAware = SpringBeanUtils.getBean(ServiceUnitAwareService.class);
//        ServiceUnitRegisterInfo serviceUnitRegisterInfo = suAware.getServiceUnitRegisterInfo(this.configuration.getApplicationName(), this.configuration.getServiceName());
//        //克隆一下
//        ServiceUnitRegisterInfo grpcRegisterInfo = JSONSerializer.deserialize(JSONSerializer.serialize(serviceUnitRegisterInfo), ServiceUnitRegisterInfo.class);
//        List<ServiceUnitInfo> serviceUnitInfos = grpcRegisterInfo.getServiceUnitInfo();
//        serviceUnitInfos.forEach(info -> info.setName(info.getName() + "-grpc"));
//
//        //注册微服务信息
//        this.serviceRegistry.register(grpcRegisterInfo,ip,Integer.valueOf(port));
        ServiceUnitDefinition definition = ServiceUnitDefinition.builder()
                .port(Integer.valueOf(port))
                .msuSuffix("-grpc")
                .build();
        ServiceCenterProvider.getServiceCenterProvider().registry(definition);
        try {
            //构造服务开启参数
            Map<String,Object> serverBuildArgs = new HashMap<>();
            serverBuildArgs.put(GrpcVariable.SERVER_PORT,Integer.valueOf(port));
            serverBuildArgs.put(GrpcVariable.SERVER_SERVICE,new GrpcServerInvoke());
            Objects.requireNonNull(RpcChannelFactory.buildChannelServer(RpcChannelType.GRPC)).startServer(serverBuildArgs);
            log.info("GrpcService has already start on port: "+port);
        } catch (Exception e) {
            log.error("gRPC Server start failed:"+e.getMessage(),e);
        }
    }
}
